<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="医生首患数量趋势图">
    <title>{{title}}</title>
    <link rel="stylesheet" href="/apps/css/bootstrap.min.css">
    <link rel="stylesheet" href="/apps/css/fontawesome-free-6.4.0-web/css/all.css">
    <link rel="stylesheet" href="/apps/css/mui.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
    <header class="d-flex align-items-center bg-custom-color p-3">
        <button id="backButton" class="btn btn-primary rounded-circle me-3" style="background-color: white;" onclick="history.back();">
            <i class="fas fa-arrow-left custom-color"></i>
        </button>
        <span class="title-text text-white fs-5">
            {{title}}
        </span>
    </header>

    <div class="container">
        <div class="content">
            <div class="row">
                <div class="col-12">
                    <div class="card mb-4">
                        <div class="card-header">
                            <h5 class="card-title mb-0">{{description}}</h5>
                        </div>
                        <div class="card-body">
                            <!-- 图表类型切换 -->
                            <div class="row mb-3">
                                <div class="col-12">
                                    <div class="btn-group w-100" role="group" aria-label="图表类型切换">
                                        <input type="radio" class="btn-check" name="chartType" id="first_order" value="first_order" {{#if (eq type "first_order")}}checked{{/if}}>
                                        <label class="btn btn-outline-primary" for="first_order">
                                            <i class="fas fa-user-check"></i> 首患数量
                                        </label>

                                        <input type="radio" class="btn-check" name="chartType" id="recruited" value="recruited" {{#if (eq type "recruited")}}checked{{/if}}>
                                        <label class="btn btn-outline-success" for="recruited">
                                            <i class="fas fa-users"></i> 推荐患者
                                        </label>

                                        <input type="radio" class="btn-check" name="chartType" id="sales" value="sales" {{#if (eq type "sales")}}checked{{/if}}>
                                        <label class="btn btn-outline-warning" for="sales">
                                            <i class="fas fa-dollar-sign"></i> 销售额
                                        </label>
                                    </div>
                                </div>
                            </div>

                            <div class="row mb-3">
                                <div class="col-md-2">
                                    <div class="text-center">
                                        <h6 class="text-muted">
                                            {{#if (eq type "first_order")}}总首患数{{else if (eq type "recruited")}}总推荐数{{else}}总销售额{{/if}}
                                        </h6>
                                        <h4 class="text-primary">{{totalValue}}</h4>
                                    </div>
                                </div>
                                <div class="col-md-2">
                                    <div class="text-center">
                                        <h6 class="text-muted">80%阈值</h6>
                                        <h4 class="text-warning">{{threshold}}</h4>
                                    </div>
                                </div>
                                <div class="col-md-2">
                                    <div class="text-center">
                                        <h6 class="text-muted">显示客户数</h6>
                                        <h4 class="text-success">{{clientCount}}</h4>
                                    </div>
                                </div>
                                {{#if rep_code}}
                                <div class="col-md-2">
                                    <div class="text-center">
                                        <h6 class="text-muted">代表代码</h6>
                                        <h4 class="text-info">{{rep_code}}</h4>
                                    </div>
                                </div>
                                {{/if}}
                                <div class="col-md-2">
                                    <div class="text-center">
                                        <h6 class="text-muted">统计期间</h6>
                                        <h6 class="text-info">{{begin}} 至 {{end}}</h6>
                                    </div>
                                </div>
                            </div>

                            {{#if chartData}}
                            <div class="alert alert-info mb-3" role="alert">
                                <i class="fas fa-info-circle"></i>
                                <strong>线条说明：</strong>
                                {{#if exclude_cid}}
                                    红色虚线表示排除C#{{exclude_cid}}后的算术平均值，蓝色实线表示排除C#{{exclude_cid}}后的合计值。
                                {{else}}
                                    红色虚线表示所有客户的算术平均值，蓝色实线表示所有客户的合计值。
                                {{/if}}
                                用于对比单个客户与整体水平的差异。
                            </div>
                            <div class="chart-container" style="position: relative; height:60vh; width:100%;">
                                <canvas id="doctorChart"></canvas>
                            </div>

                            <div class="mt-4">
                                <h6>客户列表 (按{{#if (eq type "first_order")}}总首患数{{else if (eq type "recruited")}}总推荐数{{else}}总销售额{{/if}}排序)</h6>
                                <div class="table-responsive">
                                    <table class="table table-striped table-sm">
                                        <thead class="table-light">
                                            <tr>
                                                <th>排名</th>
                                                <th>客户姓名</th>
                                                <th>代表代码</th>
                                                <th>机构</th>
                                                <th>部门</th>
                                                <th>{{#if (eq type "first_order")}}总首患数{{else if (eq type "recruited")}}总推荐数{{else}}总销售额{{/if}}</th>
                                                <th>占比</th>
                                                <th>累计占比</th>
                                                <th>操作</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            {{#each chartData}}
                                            <tr>
                                                <td>{{add @index 1}}</td>
                                                <td>{{this.name}}</td>
                                                <td>{{this.rep_code}}</td>
                                                <td>{{this.agency}}</td>
                                                <td>{{this.department}}</td>
                                                <td class="text-primary fw-bold">
                                                    {{#if (eq ../type "sales")}}
                                                        ¥{{formatNumber this.total 0}}
                                                    {{else}}
                                                        {{this.total}}
                                                    {{/if}}
                                                </td>
                                                <td>{{formatNumber this.percentage 2}}%</td>
                                                <td>{{formatNumber this.cumulativePercentage 2}}%</td>
                                                <td>
                                                    <a href="/apps/doctor-performance/detail/{{this.uid}}?begin={{../begin}}&end={{../end}}"
                                                       class="btn btn-sm btn-outline-primary">
                                                        <i class="fas fa-chart-line"></i> 详情
                                                    </a>
                                                </td>
                                            </tr>
                                            {{/each}}
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                            {{else}}
                            <div class="text-center py-5">
                                <i class="fas fa-chart-line fa-3x text-muted mb-3"></i>
                                <h5 class="text-muted">暂无数据</h5>
                                <p class="text-muted">在指定时间段内没有找到客户业绩数据</p>
                            </div>
                            {{/if}}
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <nav aria-label="Page navigation" class="pagination-container">
            <button id="homeButton" class="btn btn-primary position-absolute top-0 start-0 m-3 rounded-circle" style="width: 50px; height: 50px; padding: 0;" onclick="window.location.href='https://totemlife.cn/apps/crm/';">
                <i class="fas fa-home" style="color:white;"></i>
            </button>
            <button id="formButton" class="btn btn-primary position-absolute top-0 end-0 m-3 rounded-circle" style="width: 50px; height: 50px; padding: 0;" onclick="showQueryForm();">
                <i class="fas fa-search" style="color: white;"></i>
            </button>
        </nav>
    </div>

    <footer class="footer" style="text-align: center;">
        <div class="row">
            <div class="text-muted">&nbsp;</div>
            <div class="text-muted">&nbsp;</div>
            <div class="text-muted">&copy;2023 图腾生命医学</div>
            <div class="text-muted">我们为人类免疫事业而奉献</div>
        </div>
    </footer>

    <!-- 查询条件模态框 -->
    <div class="modal fade" id="queryModal" tabindex="-1" aria-labelledby="queryModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="queryModalLabel">设置查询条件</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="queryForm" onsubmit="submitQueryForm()">
                    <div class="modal-body">
                        <div class="row">
                            <div class="col">
                                <div class="mb-3">
                                    <label for="begin" class="form-label">开始日期</label>
                                    <input type="date" class="form-control" id="begin" name="begin" value="{{begin}}">
                                </div>
                            </div>
                            <div class="col">
                                <div class="mb-3">
                                    <label for="end" class="form-label">结束日期</label>
                                    <input type="date" class="form-control" id="end" name="end" value="{{end}}">
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-2">
                                <div class="mb-3">
                                    <label for="limit" class="form-label">显示客户数量</label>
                                    <input type="number" class="form-control" id="limit" name="limit" value="{{limit}}" min="5" max="50">
                                    <div class="form-text">建议不超过50个客户</div>
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="mb-3">
                                    <label for="type" class="form-label">图表类型</label>
                                    <select class="form-select" id="type" name="type">
                                        <option value="first_order" {{#if (eq type "first_order")}}selected{{/if}}>首患数量</option>
                                        <option value="recruited" {{#if (eq type "recruited")}}selected{{/if}}>推荐患者</option>
                                        <option value="sales" {{#if (eq type "sales")}}selected{{/if}}>销售额</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="mb-3">
                                    <label for="rep_code" class="form-label">代表代码</label>
                                    <input type="text" class="form-control" id="rep_code" name="rep_code" value="{{rep_code}}" placeholder="留空则统计所有代表">
                                    <div class="form-text">指定代表代码，如LXH</div>
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="mb-3">
                                    <label for="exclude_cid" class="form-label">排除客户CID</label>
                                    <input type="number" class="form-control" id="exclude_cid" name="exclude_cid" value="{{exclude_cid}}" placeholder="留空则不排除任何客户">
                                    <div class="form-text">指定要排除的客户CID</div>
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="mb-3">
                                    <label for="show_lines" class="form-label">显示线条</label>
                                    <select class="form-select" id="show_lines" name="show_lines">
                                        <option value="both" {{#if (eq show_lines "both")}}selected{{/if}}>默认（均值线+合计线）</option>
                                        <option value="average_only" {{#if (eq show_lines "average_only")}}selected{{/if}}>只显示均值线</option>
                                        <option value="total_only" {{#if (eq show_lines "total_only")}}selected{{/if}}>只显示合计线</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭查询</button>
                        <button type="submit" class="btn btn-primary">查询数据</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
    <script src="/apps/js/bootstrap.bundle.min.js"></script>
    <script src="/apps/js/wx-client-dom.js"></script>

    {{#if chartData}}
    <script>
        // 图表数据
        const chartData = {{{json chartData}}};
        const averageLineData = {{{json averageLineData}}};
        const totalLineData = {{{json totalLineData}}};
        const months = {{{json months}}};
        const showLines = '{{show_lines}}';

        // 生成随机颜色
        function generateColors(count) {
            const colors = [];
            const baseColors = [
                '#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF',
                '#FF9F40', '#FF6384', '#C9CBCF', '#4BC0C0', '#FF6384',
                '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF', '#FF9F40',
                '#FF6384', '#C9CBCF', '#4BC0C0', '#FF6384', '#36A2EB'
            ];

            for (let i = 0; i < count; i++) {
                colors.push(baseColors[i % baseColors.length]);
            }
            return colors;
        }

        // 创建图表
        const ctx = document.getElementById('doctorChart').getContext('2d');
        const datasets = chartData.map((doctor, index) => ({
            label: doctor.name,
            data: doctor.data,
            borderColor: generateColors(chartData.length)[index],
            backgroundColor: generateColors(chartData.length)[index] + '20',
            borderWidth: 2,
            fill: false,
            tension: 0.4,
            pointRadius: 3,
            pointHoverRadius: 6
        }));

        // 根据显示选项添加线条
        const excludeCid = '{{exclude_cid}}';
        const excludeText = excludeCid ? ` (排除C#${excludeCid})` : '';

        if (showLines === 'both' || showLines === 'average_only') {
            datasets.push({
                label: `均值线${excludeText}`,
                data: averageLineData,
                borderColor: '#FF0000',
                backgroundColor: '#FF000020',
                borderWidth: 3,
                borderDash: [5, 5],
                fill: false,
                tension: 0.4,
                pointRadius: 4,
                pointHoverRadius: 8
            });
        }

        if (showLines === 'both' || showLines === 'total_only') {
            datasets.push({
                label: '合计线',
                data: totalLineData,
                borderColor: '#0066CC',
                backgroundColor: '#0066CC20',
                borderWidth: 3,
                fill: false,
                tension: 0.4,
                pointRadius: 4,
                pointHoverRadius: 8
            });
        }

        // 根据图表类型设置标题和Y轴标签
        let chartTitle, yAxisTitle;
        switch('{{type}}') {
            case 'recruited':
                chartTitle = '医生推荐患者数量趋势图';
                yAxisTitle = '推荐患者数量';
                break;
            case 'sales':
                chartTitle = '医生销售额趋势图';
                yAxisTitle = '销售额';
                break;
            default:
                chartTitle = '医生首患数量趋势图';
                yAxisTitle = '首患数量';
                break;
        }

        new Chart(ctx, {
            type: 'line',
            data: {
                labels: months,
                datasets: datasets
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    title: {
                        display: true,
                        text: chartTitle,
                        font: {
                            size: 16
                        }
                    },
                    legend: {
                        display: true,
                        position: 'top',
                        labels: {
                            usePointStyle: true,
                            padding: 20,
                            font: {
                                size: 12
                            }
                        }
                    },
                    tooltip: {
                        mode: 'index',
                        intersect: false,
                        callbacks: {
                            title: function(context) {
                                return '月份: ' + context[0].label;
                            },
                            label: function(context) {
                                let unit = '首患';
                                switch('{{type}}') {
                                    case 'recruited':
                                        unit = '推荐';
                                        break;
                                    case 'sales':
                                        unit = '元';
                                        break;
                                    default:
                                        unit = '首患';
                                        break;
                                }

                                // 为均值线添加特殊标识
                                if (context.dataset.label.includes('均值线')) {
                                    return context.dataset.label + ': ' + context.parsed.y + ' ' + unit + ' (平均值)';
                                } else {
                                    return context.dataset.label + ': ' + context.parsed.y + ' ' + unit;
                                }
                            }
                        }
                    }
                },
                scales: {
                    x: {
                        display: true,
                        title: {
                            display: true,
                            text: '月份'
                        }
                    },
                    y: {
                        display: true,
                        title: {
                            display: true,
                            text: yAxisTitle
                        },
                        beginAtZero: true
                    }
                },
                interaction: {
                    mode: 'nearest',
                    axis: 'x',
                    intersect: false
                }
            }
        });
    </script>
    {{/if}}

        <script>
        function showQueryForm() {
            const modal = new bootstrap.Modal(document.getElementById('queryModal'));
            modal.show();
        }

        function submitQueryForm() {
            event.preventDefault();
            const queryParams = new URLSearchParams();
            const paramsToCheck = ['begin', 'end', 'limit', 'type', 'rep_code', 'exclude_cid', 'show_lines'];
            for (const param of paramsToCheck) {
                const value = document.getElementById(param).value;
                if (value && value !== '') queryParams.append(param, value);
            }
            const url = `https://totemlife.cn/apps/doctor-performance/chart?${queryParams.toString()}`;
            window.location.href = url;
        }

        // 图表类型切换功能
        document.addEventListener('DOMContentLoaded', function() {
            const chartTypeRadios = document.querySelectorAll('input[name="chartType"]');
            chartTypeRadios.forEach(radio => {
                radio.addEventListener('change', function() {
                    if (this.checked) {
                        const queryParams = new URLSearchParams(window.location.search);
                        queryParams.set('type', this.value);
                        window.location.href = `https://totemlife.cn/apps/doctor-performance/chart?${queryParams.toString()}`;
                    }
                });
            });
        });
    </script>
</body>
</html>